import { numberFormat } from '@/utils/formatterUtil';

const summaryFieldChooser = filter => header => {
    const find = columns => {
        let result = [];

        // eslint-disable-next-line no-unused-expressions
        columns &&
            columns.forEach(col => {
                if (col?.children?.length > 0) {
                    const childrenResult = find(col.children);

                    if (childrenResult?.length > 0) {
                        result = result.concat(childrenResult);
                    }
                } else {
                    const filterResult = filter(col);

                    if (typeof filterResult === 'boolean') {
                        result.push(col.dataIndex);
                    } else if (filterResult.success) {
                        result.push(filterResult.result);
                    }
                }
            });

        return result;
    };

    return find(header);
};

const numberFilter = col => {
    if (col.columnType === 1 || col.columnType === 2) {
        return {
            success: true,
            result: {
                [col.dataIndex]: (total, current) => {
                    const currentStr = String(current);
                    const dotPosition = currentStr.indexOf('.');
                    const decimalPlaces = dotPosition > -1 ? currentStr.substring(dotPosition + 1).length : 0;

                    if (current || current === 0) {
                        const newTotal = Number(total || 0) + Number(current || 0);
                        return numberFormat(newTotal, decimalPlaces, '');
                    }

                    return total;
                }
            }
        };
    }
    // SHG员工缴交金
    if (col.columnType === 6) {
        return {
            success: true,
            result: {
                [col.dataIndex]: (total, current) => {
                    const currentStr = String(current);
                    const dotPosition = currentStr.indexOf('.');
                    const decimalPlaces = dotPosition > -1 ? currentStr.substring(dotPosition + 1).length : 0;

                    if (current || current === 0) {
                        const currentList = current.toString().split('/');
                        const newTotal = currentList.reduce((all, it) => Number(all || 0) + Number(it || 0), total);
                        return numberFormat(newTotal, decimalPlaces, '');
                    }

                    return total;
                }
            }
        };
    }
    return false;
};
const andFilter = (filter1, filter2) => col => filter1(col) && filter2(col);
const orFilter = (filter1, filter2) => col => filter1(col) || filter2(col);

export { summaryFieldChooser, numberFilter, andFilter, orFilter };
